<template>
    <view class="models overview">
        <view class="models-title">
            维保中电梯总览
        </view>
        <view class="overview-num" v-if="!showDetail">
            <view class="overview-num-item">
                <view class="numblock"> 
                    {{ dataMap.inMaintain||0 }} <text>台</text>
                </view>
                <view>
                  维保中电梯总数
                </view>
            </view>
            <view class="line">

            </view>
            <view class="overview-num-item" @click.stop="showageDetail(1)">
                <div class="progress">
                    <l-echart class="progress" ref="progress1"></l-echart>
                </div>
                <div> 责任组设置率<uni-icons color="#999" type="forward" size="14"></uni-icons></div>

            </view>
            <view class="line">

            </view>
            <view class="overview-num-item" @click.stop="showageDetail(2)">
                <div class="progress">
                    <l-echart class="progress" ref="progress2"></l-echart>
                </div>
                <div> 责任人设置率<uni-icons color="#999" type="forward" size="14"></uni-icons></div>
            </view>
        </view>

        <view class="models-titled" v-if="!showDetail">
            维保中年审梯占比
        </view>
        <!-- 占比进度条 -->
        <view class="progress-inline" v-if="!showDetail">
            <view :style="{ width: auditPercentage + '%' }" />
            <view :style="{ width: notAuditPercentage + '%' }" />
        </view>
        <!-- 占比进度条 -->
        <view class="progress-infos" v-if="!showDetail">
            <view class="progress-infos-item">
                <view class="progress-infos-item-text">
                    <view class="smallcircle-filled"></view> 维保中年审梯
                </view>
                <view class="progress-infos-item-text">
                    {{ dataMap.audit }}台
                </view>
                <view class="progress-infos-item-text">
                    {{ dataMap.auditPercentage }}%
                </view>
            </view>
            <view class="progress-infos-item">
                <view class="progress-infos-item-text">
                    <view class="smallcircle-filled notFill"></view> 维保中非年审梯
                </view>
                <view class="progress-infos-item-text">
                    {{ dataMap.notAudit }}台
                </view>
                <view class="progress-infos-item-text">
                    {{ dataMap.notAuditPercentage }}%
                </view>
            </view>
        </view>

        <view class="overview-back" v-if="showDetail">
            <view class="back-btn" @click="showAllCount">
                <uni-icons type="back" size="14" color="#0091FF"></uni-icons>
                返回
            </view>
            <view class="slash">
                /
            </view>
            <view>
                {{ detailType == 1 ? '责任组设置情况' : '责任人设置情况' }}
            </view>
        </view>

        <view class="overview-num overview-conut" v-if="showDetail">
            <view class="overview-num-item">
                <view class="numblock">
                    {{ detailType == 1 ? dataMap.alreadySetDept : dataMap.alreadySetUser }} <text>台</text>
                </view>
                <view>
                    已设置责任{{ detailType == 1 ? '组' : '人' }}
                </view>
            </view>
            <view class="line">

            </view>
            <view class="overview-num-item">
                <view class="numblock noSetting">
                    {{ detailType == 1 ? dataMap.deptCount : dataMap.userCount }} <text>台</text>
                </view>
                <view @click="toElevatorList">
                    未设置责任{{ detailType == 1 ? '组' : '人' }}
                    <uni-icons color="#999" type="forward" size="14"></uni-icons>
                </view>
            </view>
        </view>
        <view class="download-btn" v-if="showDetail" @click="downloadFuc">
            <image src="@/static/images/download.png" /> 下载数据
        </view>

        <view class="loading-block" v-if="loading">
            <image class="img" src="@/static/images/loading.png" mode=""></image>

            <view class="text">加载中..</view>
        </view>

        <model :maskClick="false" width="508rpx" :visible="successVisible" title="下载成功" cancleTxt="复制链接"
            comfireTxt="直接打开" @cancle="modelRes(1)" @comfire="modelRes(2)" @close="successVisible = false">
            <view class="modelItem"> 你可以直接打开，或者复制链接至 </view>
            <view class="modelItem"> 电脑端浏览器下载。 </view>
        </model>

    </view>
</template>
<script>
import model from '@/components/model/index.vue';
import { mapState } from 'vuex';
import { setProgressPieOpt } from './chartSet.js';
import * as echarts from '@/subpages/components/lime-echart/static/echarts.min';
import LEchart from '@/subpages/components/lime-echart/components/l-echart/l-echart.vue';
import { getElevatorAllcount, getElevatorExcel } from '@/apis/statistic.js';
export default {
	components: { LEchart, model },
	props: {

	},
	data() {
		return {
			successVisible: false,
			downloadUrl: '',
			// 本地下载后的路径
			localPath: '',
			loading: false,
			dataMap: {
				alreadySetDept: 0,
				alreadySetUser: 0,
				audit: 0,
				auditPercentage: 0,
				auditRate: 0,
				deptCount: 0,
				deptCountPercentage: 0,
				deptCountRate: 0,
				inMaintain: 0,
				notAudit: 0,
				notAuditPercentage: 0,
				notAuditRate: 0,
				userCount: 0,
				userCountPercentage: 0,
				userCountRate: 0,
			},
			detailType: 0,
			showDetail: false,
			auditPercentage: 0,
			notAuditPercentage: 0,
			chartMaps: {
				progress1: null,
				progress2: null
			},
		};
	},
	computed: {
		...mapState('user', ['userinfo']),

	},
	async mounted() {
		this.getElevatorAllcount();
	},
	beforeDestroy() {
		// 清理图表实例，避免内存泄漏
		if (this.chartMaps) {
			Object.values(this.chartMaps).forEach(chart => {
				if (chart && chart.dispose) {
					try {
						chart.dispose();
					} catch (error) {
						console.warn('图表清理失败:', error);
					}
				}
			});
			this.chartMaps = {};
		}
	},
	methods: {
		toElevatorList() {
			uni.navigateTo({
				url: '/subpages/statistics/elevatorList?type=' + (this.detailType == 1 ? 1 : 2),
			});
		},
		modelRes(type) {
			if (type == 1) {
				// 复制
				uni.setClipboardData({
					data: this.downloadUrl,
					success: () => {

					},
				});
				this.successVisible = false;
			} else {
				// 直接打开

				// #ifdef H5
				// eslint-disable-next-line no-undef
				sida.openUrl({ url: this.downloadUrl });
				uni.hideLoading();
				// #endif
				// #ifdef H5
				// eslint-disable-next-line no-undef
				sida.openUrl({ url: this.downloadUrl });
				uni.hideLoading();
				// #endif

				// #ifndef h5
				uni.openDocument({
					filePath: this.localPath,
					showMenu: true,
					fileType: 'xlsx',
					success: () => {
						console.log('打开文档成功');
					},
					fail: (err) => {
						console.log(err);
					},
				});
				// #endif
				// #ifndef h5
				uni.openDocument({
					filePath: this.localPath,
					showMenu: true,
					fileType: 'xlsx',
					success: () => {
						console.log('打开文档成功');
					},
					fail: (err) => {
						console.log(err);
					},
				});
				// #endif

				this.successVisible = false;
			}
		},
		downloadFuc() {
			uni.showLoading({
				title: '下载中',
				mask: true,
			});
			getElevatorExcel({
				unsetType: this.detailType
			}).then(res => {
				let str = res.data.split('/')[res.data.split('/').length - 1];
				const downloadUrl = res.data;
				this.downloadUrl = downloadUrl;
				console.log(
					str,
					'str',
					wx.env.USER_DATA_PATH + '/' + str,
				);

				// #ifndef h5
				uni.downloadFile({
					url: res.data,
					filePath: wx.env.USER_DATA_PATH + '/' + str,
					success: (res) => {
						uni.hideLoading();
						console.log(res, '下载的文件');
						this.localPath = res.filePath;
						this.successVisible = true;
					},
					fail: (err) => {
						console.log(err, '下载失败');
						uni.hideLoading();
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						});
					}
				});
				// #endif
			});
		},
		// 绘制环形图
		setProgressChart(chart) {
			if (!this.chartMaps) {
				this.chartMaps = {};
			}
			
			// 确保数据有效性
			const percentage = Number(chart == 'progress1' ? this.dataMap.deptCountPercentage : this.dataMap.userCountPercentage);
			if (typeof percentage !== 'number' || isNaN(percentage)) {
				console.warn(`图表 ${chart} 数据无效:`, percentage);
				return;
			}
			
			const chartOpt = setProgressPieOpt({ data: percentage });
			
			this.$nextTick(() => {
				if (!this.$refs[chart]) {
					console.warn(`图表组件 ${chart} 未找到`);
					return;
				}
				
				try {
					this.$refs[chart].init(echarts, chartF => { 
						// 避免循环引用，只保存必要的引用
						this.chartMaps[chart] = {
							setOption: chartF.setOption.bind(chartF),
							dispose: chartF.dispose.bind(chartF),
							resize: chartF.resize.bind(chartF)
						};
						chartF.setOption(chartOpt);
					});
				} catch (error) {
					console.error(`图表 ${chart} 初始化失败:`, error);
				}
			});
		},

		getElevatorAllcount() {
			this.loading = true;
			getElevatorAllcount().then(res => {
				// 深拷贝数据，避免循环引用
				this.dataMap = JSON.parse(JSON.stringify(res.data));
				this.auditPercentage = this.dataMap.auditPercentage;
				this.notAuditPercentage = this.dataMap.notAuditPercentage;
				try { 
					this.$nextTick(() => {
						this.setProgressChart('progress1');
						this.setProgressChart('progress2');
					});
				} catch (error) {
					console.log('图表初始化错误:', error);
				}

				this.loading = false;
			}).catch(error => {
				console.error('获取数据失败:', error);
				this.loading = false;
			});
		}, 
		// 数据下转  type： 1组 2人
		showageDetail(type) {
			this.detailType = type;
			this.showDetail = true;
			this.auditPercentage = 0;
			this.notAuditPercentage = 0;
		},
		showAllCount() {
			this.showDetail = false;
			this.$nextTick(() => {
				this.setProgressChart('progress1');
				this.setProgressChart('progress2');
				this.auditPercentage = this.dataMap.auditPercentage;
				this.notAuditPercentage = this.dataMap.notAuditPercentage;
			});
		}
	}
};
</script>

<style lang="scss" scoped>
@import './elevator.scss';

.overview {
    position: relative;

    &-num {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 26rpx;
        padding: 40rpx 0;

        &-item {
            width: 33%;
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 160rpx;
            color: #999;

            .progress {
                height: 130rpx;
                width: 130rpx;
            }

            .numblock {
                font-size: 54rpx;
                color: #333333;
                font-weight: bold;

                width: 130rpx;
                height: 130rpx;
                display: flex;
                align-items: center;
                justify-content: center;

                text {
                    font-size: 26rpx;
                    color: #666;
                    font-weight: normal;
                    line-height: 82rpx;
                    display: inline-block;
                    height: 60rpx;
                    margin-left: 6rpx;
                }
            }
        }

        .line {
            height: 60rpx;
            width: 2rpx;
            background-color: #eeeeee;
        }
    }

    &-conut {
        justify-content: space-around;
        padding-bottom: 30px;

        .numblock {
            height: 96rpx;
        }

        .noSetting {
            color: #FA6400;
        }
    }

    &-back {
        width: 100%;
        display: flex;
        font-size: 26rpx;
        align-items: center;
        color: #333;
        margin-top: 12rpx;

        .back-btn {
            color: #0091FF;
        }

        .slash {
            color: #999;
            margin: 0 6rpx;
        }
    }

    .download-btn {
        position: absolute;
        right: 104rpx;
        bottom: 40rpx;
        color: #666;
        font-size: 26rpx;

        image {
            width: 1rem;
            height: 1rem;
            margin-right: 2rpx;
            vertical-align: -0.18rem;
        }
    }
}

.progress-inline {
    width: 100%;
    height: 16rpx;
    background-color: #DCF0FF;
    // background: #7debb8;
    border-radius: 10rpx;
    overflow: hidden;
    display: flex;

    view {
        width: 0;
        transition: 1s all;
        height: 100%;
    }

    view:nth-child(1) {
        background: #0091ff;
    }

    view:nth-child(2) {
        background: #7DEBB8;
    }
}

.progress-infos {
    width: 100%;
    margin-top: 24rpx;

    &-item {
        display: flex;
        width: 100%;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16rpx;
        color: #666;

        &-text {
            width: 33%;
            text-align: right;

            .smallcircle-filled {
                display: inline-block;
                width: 16rpx;
                height: 16rpx;
                background: #0091ff;
                border-radius: 50%;
                vertical-align: 0.06rem;
                margin-right: 10rpx;
            }

            .notFill {
                background: #7DEBB8
            }
        }

        &-text:first-child {
            flex: 1;
            text-align: left;
        }

        &-text:nth-child(2) {
            width: 25%;
            text-align: center;
        }
    }
}

.modelItem {
    display: flex;
    justify-content: center;
    font-size: 28rpx;
    color: #333;
}
</style>
